package org.hxzon.configdesigner.web.pages;

import java.util.Collection;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.hxzon.configdesigner.core.CfgInfo;
import org.hxzon.configdesigner.core.CfgParser;
import org.hxzon.configdesigner.core.CfgValue;
import org.hxzon.configdesigner.web.pages.base.PageBase;
import org.hxzon.configdesigner.web.util.CfgUtil;

public class ChangeValueType extends PageBase {

    @Property
    private CfgValue cfg;
    @Property
    private Collection<CfgValue> cfgs;
    @Property
    private CfgValue c;//for loop
    //
    @InjectPage
    private View pageView;

    @OnEvent(EventConstants.ACTIVATE)
    Object init(int indexCode) {
        cfg = CfgUtil.findCfg(indexCode);
        if (!cfg.isSimpleValue()) {
            return pageView.withInit(cfg.getParent().indexCode());
        }
        cfgs = CfgUtil.findCfg(cfg.getCfgInfo());
        return null;
    }

    @OnEvent(EventConstants.SUBMIT)
    Object submit() {
        CfgInfo cfgInfo = cfg.getCfgInfo();
        for (CfgValue c : cfgs) {
            converValue(c, cfgInfo);
        }
        return pageView.withInit(cfg.getParent().indexCode());
    }

    private void converValue(CfgValue c, CfgInfo cfgInfo) {
        Object origValue = c.getValue();
        Object newValue = CfgParser.convertValue(origValue, cfgInfo);
        c.setValue(newValue);
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object toPassivate() {
        return cfg.indexCode();
    }
}
